package com.example.demovote.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demovote.entity.Record;
import com.example.demovote.mapper.RecordMapper;
import com.example.demovote.service.IRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demovote.service.ServiceException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 投票系统-投票记录表-6 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-03-18
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements IRecordService {

    @Transactional
    public void commit(int vid, int usid, int[] iids) throws ServiceException {
        if(iids==null || iids.length==0){
            throw new ServiceException(-1,"请选择选项");
        }

        LambdaQueryWrapper<Record> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Record::getVid, vid);
        lqw.eq(Record::getUsid, usid);
        if (this.count(lqw)>0) {
            throw new ServiceException(-2,"您已经投过票了");
        }

        Record record = new Record();
        record.setVid(vid);
        record.setUsid(usid);
        for (int iid : iids) {
            record.setId(null);
            record.setIid(iid);
            this.save(record);
        }
    }

}
